# -*- coding: utf-8 -*-
"""测试配置文件

此文件包含pytest的fixture配置，用于测试环境的设置和资源管理。
"""

import pytest
import json
from unittest.mock import Mock
from app import create_app
from app.extensions import db


@pytest.fixture(scope='module')
def test_app():
    """创建测试Flask应用实例
    
    Returns:
        Flask测试应用实例
    """
    # 创建测试配置的应用
    app = create_app('testing')
    app.config.update({
        'TESTING': True,
        'SQLALCHEMY_DATABASE_URI': 'sqlite:///:memory:',  # 使用内存数据库
        'SQLALCHEMY_TRACK_MODIFICATIONS': False,
        'SECRET_KEY': 'test-secret-key',
        'JWT_SECRET_KEY': 'test-jwt-secret-key'
    })
    
    yield app


@pytest.fixture(scope='module')
def test_client(test_app):
    """创建测试客户端
    
    Args:
        test_app: 测试Flask应用实例
    
    Returns:
        Flask测试客户端
    """
    return test_app.test_client()


@pytest.fixture(scope='module')
def init_database(test_app):
    """初始化测试数据库
    
    Args:
        test_app: 测试Flask应用实例
    """
    with test_app.app_context():
        # 创建所有表
        db.create_all()
        
        # 可以在这里添加测试数据
        
        yield db
        
        # 测试结束后清理数据库
        db.drop_all()

@pytest.fixture(scope='function')
def test_user(test_client, init_database):
    """创建测试用户并登录，返回JWT令牌
    
    Args:
        test_client: Flask测试客户端
        init_database: 初始化的测试数据库
    
    Returns:
        JWT访问令牌
    """
    import random
    import string
    
    # 生成随机用户名和邮箱，确保唯一性
    random_suffix = ''.join(random.choices(string.ascii_lowercase + string.digits, k=6))
    user_data = {
        'username': f'testuser_{random_suffix}',
        'email': f'test_{random_suffix}@example.com',
        'password': 'testpassword'
    }
    
    # 创建用户
    test_client.post('/api/v1/users/', 
                    data=json.dumps(user_data),
                    content_type='application/json')
    
    # 登录获取令牌
    login_response = test_client.post('/api/v1/users/login', 
                                    data=json.dumps({
                                        'username': user_data['username'],
                                        'password': user_data['password']
                                    }),
                                    content_type='application/json')
    
    return login_response.json['access_token']


@pytest.fixture
def mock_openai_client():
    """Mock OpenAI客户端
    
    Returns:
        模拟的OpenAI客户端
    """
    mock_client = Mock()
    mock_response = Mock()
    mock_response.message = Mock()
    mock_response.message.content = "这是测试AI回复内容"
    mock_client.chat.completions.create.return_value = mock_response
    return mock_client


@pytest.fixture
def mock_model_service(monkeypatch):
    """Mock ModelService
    
    Args:
        monkeypatch: pytest monkeypatch fixture
    
    Returns:
        模拟的ModelService实例
    """
    mock_service = Mock()
    monkeypatch.setattr('app.api.v1.conversations.routes.ModelService', mock_service)
    return mock_service


@pytest.fixture
def sample_conversation(test_user, init_database):
    """创建示例对话
    
    Args:
        test_user: 测试用户JWT令牌
        init_database: 初始化的测试数据库
    
    Returns:
        对话实例
    """
    from app.models.conversation import Conversation
    from datetime import datetime
    
    conversation = Conversation(
        user_id=1,  # 假设第一个用户的ID为1
        title="测试对话",
        created_at=datetime.utcnow(),
        updated_at=datetime.utcnow()
    )
    
    db.session.add(conversation)
    db.session.commit()
    
    return conversation


@pytest.fixture
def sample_messages(init_database, sample_conversation):
    """创建示例消息
    
    Args:
        init_database: 初始化的测试数据库
        sample_conversation: 示例对话
    
    Returns:
        消息实例列表
    """
    from app.models.message import Message
    from datetime import datetime
    
    messages = [
        Message(
            conversation_id=sample_conversation.id,
            role='user',
            content='你好，这是一个测试消息',
            created_at=datetime.utcnow()
        ),
        Message(
            conversation_id=sample_conversation.id,
            role='assistant', 
            content='你好！很高兴为你服务。',
            created_at=datetime.utcnow()
        )
    ]
    
    for message in messages:
        db.session.add(message)
    
    db.session.commit()
    
    return messages
